/*
 * @Description:
 * @Author: ldx
 * @Date: 2022-04-07 10:12:48
 * @LastEditors: ldx
 * @LastEditTime: 2022-09-25 21:37:44
 */
import { Breadcrumb, Spin } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import { Link, useLocation } from 'react-router-dom'

import { routes as initRoutes, RoutesType } from '@/router/routes'

import styles from './index.module.less'
const findRoute = (
  match: string,
  routes: RoutesType[]
): RoutesType | undefined => {
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i]
    const { path, routes: childRoutes } = route
    if (match === path) {
      return route
    }
    if (childRoutes && childRoutes.length > 0) {
      const route = findRoute(match, childRoutes)
      if (route) return route
    }
  }
}

export const PageContainer = (props: {
  children?: React.ReactNode
  content?: (() => React.ReactNode) | string
  subText?: (() => React.ReactNode) | string
  loading?: boolean
  className?: string
}) => {
  const location = useLocation()
  // let extraBreadcrumbCurrent = ''
  const pathSnippets = location.pathname.split('/').filter((i) => i)

  let routes = initRoutes as RoutesType[]
  const extraBreadcrumbItems = pathSnippets.map((_, index) => {
    const url = `/${pathSnippets.slice(0, index + 1).join('/')}`
    // extraBreadcrumbCurrent = breadcrumbNameMap[url]
    const route = findRoute(url, routes)!

    routes = route.routes || []
    return (
      <Breadcrumb.Item key={url}>
        <Link to={route.redirect || route.path}>{route.title}</Link>
      </Breadcrumb.Item>
    )
  })
  // const breadcrumbItems = [
  //   <Breadcrumb.Item key="home">
  //     <Link to="/">首页</Link>
  //   </Breadcrumb.Item>
  // ].concat(extraBreadcrumbItems)

  return (
    <div className={`${styles.pageContainer} bg-#010529`}>
      <div className={`${styles.containerWarp} bg-#010529`}>
        <Breadcrumb>{extraBreadcrumbItems}</Breadcrumb>
      </div>
      <div
        className={`${styles.content} bg-#010529 ${props.className} p-20px `}
        style={{
          height: `calc(100% - ${54}px)`,
          overflow: props.loading ? 'hidden' : 'auto'
        }}
      >
        {props.loading === undefined ? (
          props.children
        ) : (
          <Spin spinning={props.loading}>{props.children}</Spin>
        )}
      </div>
    </div>
  )
}
